package com.xzy.cinematicket.dao.impl;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import com.xzy.cinematicket.dao.ITicketDao;
import com.xzy.cinematicket.entity.PageBean;
import com.xzy.cinematicket.entity.Shows;
import com.xzy.cinematicket.entity.Ticket;
import com.xzy.cinematicket.util.DbUtil;

/**
 * @author yihuan.Zhou
 *
 * @Date 下午3:39:29
 */
public class TicketDaoImpl implements ITicketDao{
	QueryRunner qr = new QueryRunner(DbUtil.getDataSource());
	
	@Override
	public int insert(Ticket ticket) {
		int flag = -1;
		String sql = " insert into ticket values(null,?,?,?) ";
		Object[] params ={ticket.getUid(),ticket.getSid(),ticket.getSeatNumber()};
		try {
			flag = qr.update(sql, params);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return flag;
	}

	@Override
	public List<Ticket> selectByUid(int uid) {
		List<Ticket> list = null;
		String sql = " select * from ticket where uid = ? ";
		try {
			list = qr.query(sql, new BeanListHandler<Ticket>(Ticket.class), uid);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return list;
	}
	
	public List<Ticket> selectBySid(int sid) {
		List<Ticket> list = null;
		String sql = " select * from ticket where sid = ? ";
		try {
			list = qr.query(sql, new BeanListHandler<Ticket>(Ticket.class), sid);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return list;
	}

	@Override
	public List<Ticket> getPageList(PageBean<Ticket> page, int uid) {
		page.setTotalCount(count(uid));
		List<Ticket> list = null;
		try {
			String sql = " select * from ticket where uid = ? limit ? ,?";
			Object params[] = {uid, (page.getCurrentPage() - 1)*page.getPageCount(), page.getPageCount()};
			list = qr.query(sql,new BeanListHandler<Ticket>(Ticket.class), params);
			page.setTotalPage();
			page.setPageList(list);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return list;
	}

	@Override
	public int count(int uid) {
		long flag = 0;
		String sql = " select count(*) from ticket where uid = ? ";
		try {
			flag = qr.query(sql, new ScalarHandler<>(), uid);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return (int)flag;
	}
}
